package com.bole.Thread;

import com.alibaba.fastjson.JSONObject;
import com.bole.dto.car.TbCarDto;
import com.bole.dto.car.TbCarInfoDto;
import com.bole.dto.img.TbCarImgDto;
import com.bole.feign.CarFeign;
import com.bole.feign.CarInfoFeign;
import com.bole.feign.TbCarImgFeign;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.persistence.Column;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//@Component
public class CarpageThred implements Runnable {
    private Template template;
    private Map map;
    private String outPath;
    private Long carId;
    private Lock lock = new ReentrantLock(true);
    public CarpageThred(Template template, Map map, String outPath, Long carId) {
        this.template = template;
        this.map = map;
        this.outPath = outPath;
        this.carId = carId;
    }

    public Template getTemplate() {
        return template;
    }

    public void setTemplate(Template template) {
        this.template = template;
    }

    public Map getMap() {
        return map;
    }

    public void setMap(Map map) {
        this.map = map;
    }

    public String getOutPath() {
        return outPath;
    }

    public void setOutPath(String outPath) {
        this.outPath = outPath;
    }

    public Long getCarId() {
        return carId;
    }

    public void setCarId(Long carId) {
        this.carId = carId;
    }

    @Override
    public void run() {
        lock.lock();
        try {

            makePage();
        } finally {
            lock.unlock();
        }
    }

    public void makePage() {
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(outPath + carId + ".html");
            template.process(map, fileWriter);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } finally {
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
